<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>

    <script type="text/javascript">
        var ws;
        function WebSocketTest()
        {
            if ("WebSocket" in window)
            {
                console.log("您的浏览器支持 WebSocket!");

                // 打开一个 web socket
                if(ws==null)
                ws = new WebSocket("ws://localhost:8888");

                ws.onopen = function()
                {
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    ws.send("发送的数据");
                    console.log("数据发送中...");
                };

                ws.onmessage = function (evt)
                {
                    var received_msg = evt.data;
                    console.log("数据已接收..."+received_msg);
                };

                ws.onclose = function()
                {
                    // 关闭 websocket
                    alert("连接已关闭...");
                };
            }

            else
            {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }
        var index=1;
        function sendMessage() {
            if (ws != null) {
                var input = document.getElementById("message");
                ws.send(input.value);
            }
        }
        function WebSocketClose() {
            if (ws != null) {
                ws.close()
            }
        }
    </script>

</head>
<body>

<div id="sse">
    <a href="javascript:WebSocketTest()">运行 WebSocket</a>
    <input style="display:block;" id="message"/>
    <a style="display: block" href="javascript:sendMessage()">发送信息</a>
    <a style="display: block" href="javascript:WebSocketClose()">关闭 WebSocket</a>
</div>

</body>
</html>